//
//  HKAlertView.swift
//  HKUtilitySwift
//
//  Created by 胡锦涛 on 2018/12/21.
//  Copyright © 2018 胡锦涛. All rights reserved.
//

import UIKit
private var alertWindow: UIWindow = UIWindow.init(frame: CGRect.zero)

fileprivate class HKAlertController: UIView {
    
    static var shard: HKAlertController = HKAlertController()
    
    private let label = UILabel()
    
    private var count = 0
    
    init() {
        super.init(frame: CGRect.zero)
        backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.3)
        alertWindow.backgroundColor = UIColor.clear
        alertWindow.windowLevel = UIWindow.Level.alert - 1
        alertWindow.layer.cornerRadius = 5
        alertWindow.layer.masksToBounds = true
        label.textColor = UIColor.white
        label.numberOfLines = 0
        addSubview(label)
        label.textAlignment = .center
        label.font = UIFont.systemFont(ofSize: 13)
        alertWindow.addSubview(self)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate func present(weakAlert: String) {
        label.text = weakAlert
        let size = (weakAlert as NSString).boundingRect(with: CGSize.init(width: UIScreen.main.bounds.width - 160, height: 300), options: .usesLineFragmentOrigin, attributes: [.font: label.font], context: nil)
        var height: CGFloat = 44.0
        if size.height > 34 {
            height = size.height + 10.0
        }
        alertWindow.frame = CGRect.init(x: 70, y: (UIScreen.main.bounds.height - height)/2, width: UIScreen.main.bounds.width - 140, height: height)
        frame = alertWindow.bounds
        label.frame = bounds
        alertWindow.makeKeyAndVisible()
        count += 1
        let lastCount = count
        DispatchQueue.global().async {
            Thread.sleep(forTimeInterval: 2)
            DispatchQueue.main.async { [weak self] in
                self?.dismiss(lastCount)
            }
        }
    }
    
    private func dismiss(_ lastCount: Int) {
        guard lastCount == count else {
            return
        }
        let window = UIApplication.shared.windows.filter{$0.windowLevel == UIWindow.Level.normal}.first
        window?.makeKeyAndVisible()
        alertWindow.isHidden = true
        count = 0
    }
    
}
public func hk_showMessage(_ message: String) {
    HKAlertController.shard.present(weakAlert: message)
}

